package com.biu.billiards.utils;
import com.alibaba.fastjson.JSONObject;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

public class WxQrCode {
   // private static final String GETWXACODEUNLIMIT_URL = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%s";

    private static final String GETWXACODEUNLIMIT_URL = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=%s";
    private static final String URL_GET_TOKEN = "https://api.weixin.qq.com/cgi-bin/token";//获取access_token地址
    private static final String APP_ID = "wx4f370209e3d17631";// 小程序appid
    private static final String APP_SECRET = "41bde00c1e10a408d974ca09c7204853"; // 小程序秘钥




    public static final String PATH_HOME = "page_order/stage/stage";
    private static final String BASE_PREFIX = "data:image/png;base64,"; // base64图片固定前缀

    /**
     * 获取微信Access_Token
     * @param appid
     * @param secret
     * @return
     */
    public static String getWeixinAccessToken(String appid, String secret){
        String url = URL_GET_TOKEN;
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("grant_type", "client_credential");
        paramMap.put("appid", appid);
        paramMap.put("secret", secret);
        String content = HttpClientUtil.doGet(url, paramMap);

        Map map = (Map) JsonMapper.fromJson(content, HashMap.class);

       // Map map = (Map) JsonMapper.fromJson(content, HashMap.class);
        return (String)map.get("access_token");
    }

    /**
     * 生成小程序码返回base64字符串
     * @param sceneStr 要携带的参数
     * @param accessToken 上面方法得到的token
     * @param page 要跳转的小程序页面（必须是已发布的）
     * @return
     */
    public static String getminiqrQr(String scene,Integer with,String page) {
        HttpURLConnection httpURLConnection = null;
        try {
            String accessToken ;

            accessToken = getWeixinAccessToken(APP_ID,APP_SECRET);

            System.out.println("aazxsssss");
            System.out.println(accessToken);

            //  String accessToken = getWeixinAccessToken(APP_ID,APP_SECRET);


            URL url = new URL(String.format(GETWXACODEUNLIMIT_URL,accessToken));
            System.out.println("urlaaaa");
            System.out.println(url);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");// 提交模式
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
            // 发送请求参数
            JSONObject paramJson = new JSONObject();


//            paramJson.put("scene", scene);
        //    paramJson.put("access_token", accessToken);
            paramJson.put("path", page);
           // paramJson.put("width", with);

            //  paramJson.put("line_color", "\"r\":0,\"g\":0,\"b\":0");

            //  paramJson.put("auto_color", true);
           // paramJson.put("is_hyaline", true);

            printWriter.write(paramJson.toString());
            // flush输出流的缓冲
            printWriter.flush();
            //开始获取数据

            BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
            System.out.println("bis2212");
            System.out.println(bis);
            try (InputStream is = httpURLConnection.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream();){
                byte[] buffer = new byte[1024];
                int len = -1;
                while ((len = is.read(buffer)) != -1) {
                    baos.write(buffer, 0, len);
                }




                return BASE_PREFIX + Base64.getEncoder().encodeToString(baos.toByteArray());
            }
        } catch (Exception e) {

            e.printStackTrace();
        }finally {
            if (httpURLConnection != null){
                httpURLConnection.disconnect();
            }
        }
        return null;
    }



    /**
     * 模拟调用
     * 前端图片展示即可 <img src="xxx">
     * @param args
     */
    public static void main(String[] args) throws GeneralSecurityException {

       // MailUtil.sendMail("7161876@qq.com","您有积分提现申请，请抓紧审核！","提现申请");

//        String accessToken = getWeixinAccessToken(APP_ID,APP_SECRET);
    //    String qrBase64  = getminiqrQr(400,PATH_HOME);
     //   System.out.println(qrBase64);
    }
}
